#include "pfmimage.h"
#include <QFile>
#include <QDataStream>
#include <QTextStream>
#include <stdio.h>
PFMImage::PFMImage()
{
    w=h=c=0;
    pixelBuffer = NULL;
}

PFMImage::~PFMImage()
{
    if(pixelBuffer)
    {
        delete[] pixelBuffer;
        pixelBuffer = NULL;
    }
}

PFMImage::PFMImage(short width, short height, short channels, float* buffer)
{
   CreatePixelBuffer(width, height, channels, buffer);
}

void PFMImage::CreatePixelBuffer(short width, short height, short channels, float* buffer)
{
    w = width;
    h = height;
    c = channels;
    pixelBuffer = new float[w*h*c*sizeof(float)];
    if(buffer)
        memcpy(pixelBuffer, buffer, w*h*c*sizeof(float));
    else
        memset(pixelBuffer, 0, w*h*c*sizeof(float));
}

void PFMImage::WriteToFile(QString filename)
{

    QString str;
    if(c==3)
    {
        str = QString("PF \n%1 %2 \n-1.0\n").arg(w).arg(h);
    }
    if(c==1)
    {
        str = QString("Pf \n%1 %2 \n-1.0\n").arg(w).arg(h);
    }

    QFile file(filename);
    file.open(QIODevice::WriteOnly);

    QDataStream out(&file);

    for(int i=0; i<str.length(); i++)
    {
        out<<quint8(str[i].toLatin1());
    }

    out.writeRawData((char*)pixelBuffer, w*h*c*sizeof(float));

    file.close();


}

void PFMImage::ReadFromFile(QString filename)
{
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly))
           return;

    QDataStream in(&file);

    int headerSize = 0;

    QByteArray line;

    line = file.readLine();
    headerSize += line.size();


    if(line[1] == 'f')
    {
        c = 1;
    }
    if(line[1] == 'F')
    {
        c = 3;
    }
    line = file.readLine();
    headerSize += line.size();
    QTextStream txtStream(line);

    int a;
    txtStream >> a;
    w = a;
    txtStream >> a;
    h = a;

    line = file.readLine();
    headerSize += line.size();

//    in.skipRawData(headerSize);
//    in.setByteOrder(QDataStream::LittleEndian);

    pixelBuffer = new float[w*h*c*sizeof(float)];
    memset(pixelBuffer,0, w*h*c*sizeof(float));
    in.readRawData((char*)pixelBuffer, w*h*c*sizeof(float));


    file.close();
}

QVector3D PFMImage::GetPixelValue(short u, short v)
{
    QVector3D color;
    if(pixelBuffer == NULL)
        return QVector3D(0,0,0);
    v = h -1 - v;

    color.setX(pixelBuffer[(v*w+u)*3]);
    color.setY(pixelBuffer[(v*w+u)*3+1]);
    color.setZ(pixelBuffer[(v*w+u)*3+2]);

    return color;

}

void PFMImage::SetPixelValue(short u, short v, QVector3D color)
{
    v = h -1 - v;
    if(pixelBuffer == NULL)
        return;
    pixelBuffer[(v*w+u)*3] = color.x();
    pixelBuffer[(v*w+u)*3+1] = color.y();
    pixelBuffer[(v*w+u)*3+2] = color.z();
}



